﻿using AutoMapper;
using System;
using System.Collections.Generic;
using System.Text;
using xiaodingmarket_application.ViewModel;
using xiaodingmarket_Domain.Commands;
using xiaodingmarket_Domain.Commands.Order;
using xiaodingmarket_Domain.Commands.User;
using xiaodingmarket_Domain.Models;

namespace xiaodingmarket_application.Automapper
{
    public class AutoMapperConfig
    {
        public static MapperConfiguration RegisterMappings()
        {
            //创建AutoMapperConfiguration, 提供静态方法Configure，一次加载所有层中Profile定义 
            //MapperConfiguration实例可以静态存储在一个静态字段中，也可以存储在一个依赖注入容器中。 一旦创建，不能更改/修改。
            return new MapperConfiguration(cfg =>
            {
                //这个是领域模型 -> 视图模型的映射，是 读命令
                cfg.AddProfile(new DomainToViewModelMappingProfile());
                //这里是视图模型 -> 领域模式的映射，是 写命令
                cfg.AddProfile(new ViewModelToDomainMappingProfile());
            });
        }
    }

    internal class ViewModelToDomainMappingProfile : Profile
    {
        public ViewModelToDomainMappingProfile()
        {
            CreateMap<CommodityViewModel, CreateNewCommodityCommand>()
               .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.CommodityId));//属性名称不一样
            CreateMap<CommodityViewModel, UpdateCommodityCommand>()
                .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.CommodityId));//属性名称不一样
            CreateMap<CommodityViewModel, ReviewCommodityCommand>()
                .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.CommodityId));




            CreateMap<OrderViewModel, CreateNewOrderCommand>();
            CreateMap<OrderViewModel, UpdateOrderCommand>();

            CreateMap<UserViewModel, CreateUserCommand>();
        }
    }
    /// <summary>
    /// 配置构造函数，用来创建关系映射
    /// </summary>
    internal class DomainToViewModelMappingProfile : Profile
    {
        public DomainToViewModelMappingProfile()
        {
            CreateMap<Commodity, CommodityViewModel>()
                .ForMember(dest => dest.CommodityId, opt => opt.MapFrom(src => src.Id))
                .ForMember(dest => dest.Detile, opt => opt.MapFrom(src => src.CommodityDetail.Detile))
                .ForMember(dest => dest.Title, opt => opt.MapFrom(src => src.CommodityDetail.Title))
                .ForMember(dest => dest.Price, opt => opt.MapFrom(src => src.CommodityDetail.Price))
                 .ForMember(dest => dest.StudentId, opt => opt.MapFrom(src => src.CommodityDetail.StudentId));
            CreateMap<OrderCommodity, OrderViewModel>();
            CreateMap<User, UserViewModel>();
            CreateMap<ReviewCommodityCommand, CommodityViewModel>()
                .ForMember(dest => dest.CommodityId, opt => opt.MapFrom(src => src.Id));//属性名称不一样
        }
    }
}
